package com.ruoyi.project.system.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.KeyUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.system.entity.SysTenant;
import com.ruoyi.project.system.entity.SysUser;
import com.ruoyi.project.system.mapper.SysTenantMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISysTenantService;
import com.ruoyi.project.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 租户信息Service业务层处理
 *
 * @author leslie1015
 * @date 2020-07-11
 */
@Service
public class SysTenantServiceImpl implements ISysTenantService {
    @Autowired
    private SysTenantMapper sysTenantMapper;


    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ISysUserService userService;

    @Value("${sys.default.pwd}")
    private String defaultPwd;

    /**
     * 0否1是
     */
    private static final Integer FLAG_NO = 0, FLAG_YES = 1;

    /**
     * 查询租户信息
     *
     * @param id 租户信息ID
     * @return 租户信息
     */
    @Override
    public SysTenant selectSysTenantById(Long id) {
        return sysTenantMapper.selectSysTenantById(id);
    }

    /**
     * 查询租户信息列表
     *
     * @param sysTenant 租户信息
     * @return 租户信息
     */
    @Override
    public List<SysTenant> selectSysTenantList(SysTenant sysTenant) {
        return sysTenantMapper.selectSysTenantList(sysTenant);
    }

    /**
     * 新增租户信息
     *
     * @param sysTenant 租户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSysTenant(SysTenant sysTenant) {
//        sysTenant.setId(KeyUtils.genUniqueKey());
        sysTenant.setComCode(getComCode());
        sysTenant.setCreateTime(DateUtils.getNowDate());
        if (null == sysTenant.getActiveFlag()) {
            sysTenant.setActiveFlag(FLAG_YES);
        }
        if (StringUtils.isBlank(sysTenant.getPhone())) {
            throw new CustomException("电话不能为空");
        }
        if (null == sysTenant.getTempId()) {
            throw new CustomException("请选择权限模板");
        }
        if (sysTenantMapper.insertSysTenant(sysTenant) <= 0) {
            throw new CustomException("添加租户失败");
        }
        return addDefaultUser(sysTenant);
    }

    /**
     * 添加默认用户
     *
     * @param sysTenant
     */
    private Integer addDefaultUser(SysTenant sysTenant) {
        SysUser user = new SysUser();
        user.setUserName(sysTenant.getPhone());
        user.setPhonenumber(sysTenant.getPhone());
        user.setNickName("管理员" + sysTenant.getComCode());
        user.setEmail(sysTenant.getEmail());
        user.setStatus("0");//0正常1停用
        user.setCreateBy("superAdmin");
        user.setCreateTime(new Date());
        user.setRemark("租户管理员账号");
        user.setTenantId(sysTenant.getId());
        user.setAdminFlag(FLAG_YES);//是否管理员0否1是
        user.setSuperAdminFlag(FLAG_NO);//是否平台超级管理员
        user.setPassword(SecurityUtils.encryptPassword(defaultPwd));
        checkUser(user);
        return userMapper.insertUser(user);
    }

    /**
     * 校验用户信息
     *
     * @param user
     */
    private void checkUser(SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            throw new CustomException("新增用户'" + user.getUserName() + "'失败，该登录账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            throw new CustomException("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            throw new CustomException("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
    }

    private synchronized Integer getComCode() {
        Integer comCode = KeyUtils.genComCode();
        Integer count = sysTenantMapper.countByComCode(comCode);
        if (null != count && count > 0) {
            return getComCode();
        }
        return comCode;
    }

    /**
     * 修改租户信息
     *
     * @param sysTenant 租户信息
     * @return 结果
     */
    @Override
    public int updateSysTenant(SysTenant sysTenant) {
        return sysTenantMapper.updateSysTenant(sysTenant);
    }

    /**
     * 批量删除租户信息
     *
     * @param ids 需要删除的租户信息ID
     * @return 结果
     */
    @Override
    public int deleteSysTenantByIds(String[] ids) {
        return sysTenantMapper.deleteSysTenantByIds(ids);
    }

    /**
     * 删除租户信息信息
     *
     * @param id 租户信息ID
     * @return 结果
     */
    @Override
    public int deleteSysTenantById(String id) {
        return sysTenantMapper.deleteSysTenantById(id);
    }
}
